package chuangyi.com.org.ViewModel;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.View;

import java.io.File;

import chuangyi.com.org.DOMIHome.PopupActivity;
import chuangyi.com.org.DOMIHome.WaitActivityResult;

/**
 * Created by zxh on 16/11/24.
 */
public class SelectPhotoModel extends ContextObservable implements WaitActivityResult {

    public SelectPhotoModel(Context context){
        super(context);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == Activity.RESULT_CANCELED)
            return;
        Uri uri = null;
        Activity activity = (Activity)getContext();
        Intent intent = activity.getIntent();
        switch (requestCode){
            case PopupActivity.REQUEST_PHOTO:
                uri = data.getData();
                break;
            case PopupActivity.REQUEST_CAMERA:
                File file = getContext().getExternalCacheDir();
                file = new File(file.getPath() + "/avatar.jpg");
                uri = Uri.fromFile(file);
                break;
        }
        intent.setData(uri);
        activity.setResult(resultCode, intent);
        activity.finish();
    }

    public void onClickCamera(View view){
        Activity activity = (Activity)getContext();
        Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = getContext().getExternalCacheDir();
        if(file.exists() == false) {
            file.mkdir();
        }
        file = new File(file.getPath() + "/avatar.jpg");
        // 判断存储卡是否可用，存储照片文件

        intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));

        activity.startActivityForResult(intentFromCapture, PopupActivity.REQUEST_CAMERA);
    }

    public void onClickPicture(View view){
        Activity activity = (Activity)getContext();

        Intent intentFromGallery = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // 设置文件类型
        intentFromGallery.setType("image/*");
//        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        activity.startActivityForResult(intentFromGallery, PopupActivity.REQUEST_PHOTO);
    }

    public void onClickFinish(View view){
        Activity activity = (Activity)getContext();
        activity.setResult(Activity.RESULT_CANCELED);
        activity.finish();
    }

    public void onClickCancel(View view){
        Activity activity = (Activity)getContext();
        activity.setResult(Activity.RESULT_CANCELED);
        activity.finish();
    }
}
